<template>
  <div :class="'page' + (!isSingQuesMod ? ' fixed' : '')">
    <div class="p-hd" ref="pageHead">
      <template v-if="!isSingQuesMod">
        <answer-top-title :title="title" v-if="isExam"></answer-top-title>
        <div class="hd">
          <div class="op-l">
            <el-button
              type="primary"
              plain
              :class="'btn' + (showQuestionContent ? ' on' : '')"
              @click="handleViewQuestion"
              >查看题目</el-button
            >
          </div>
          <div class="hd-c-wrap">
            <div class="hd-c">
              <p class="time" v-if="isExam && time">
                总剩余时间：<span>{{ time }}</span>
              </p>
              <p class="tit" v-if="!isSingQuesMod && !isExam">{{ title }}</p>
              <p class="notice">请及时点击[保存]按钮以保存当前编辑内容，并点右上角[关闭]按钮退出编程界面</p>
            </div>
          </div>
          <div class="op-r">
            <el-button type="primary" plain class="btn" @click="handleClose">关闭</el-button>
            <el-button type="primary" class="btn" @click="handleSave">保存</el-button>
          </div>
        </div>
      </template>
      <question-detail-head
        v-if="isSingQuesMod"
        :title="title"
        :onSave="handleSave"
        :questionTypeName="questionTypeName"
      ></question-detail-head>
    </div>
    <div
      :class="'p-main clearfix' + (showQuestionContent || showAnalysis || showHistory ? ' side-on' : '')"
      :style="{ height: pageBodyHeight + 'px', margin: '0 10px' }"
    >
      <div class="side-sheet">
        <p :class="`q-cont ${canNotSelectQuestion ? 'limited' : ''}`" v-if="showQuestionContent">
          <span v-html="quesData.questionContent"></span> {{ quesData.score ? '（' + quesData.score + '分）' : '' }}
        </p>
        <div class="ana-box" v-if="!isExam && showAnalysis">
          <answer-analysis :analysisData="analysisData" :questionType="5" :lang="quesData.lang"></answer-analysis>
        </div>
        <div class="his-box">
          <commit-history
            v-if="!isExam && showHistory"
            :type="5"
            :historyData="historyData"
            :onDelete="onDeleteCommitHistory"
            :lang="quesData.lang"
          ></commit-history>
        </div>
      </div>
      <div class="edit-area">
        <iframe
          :src="`${PROGRAMURL}${langName}/?token=${token}${quesData.answer ? `&codeUrl=${quesData.answer}` : ''}`"
          ref="iframe"
          style="min-height:680px;"
        ></iframe>
      </div>
    </div>
    <div style="margin:0 10px">
      <answer-page-foot
        ref="pageFoot"
        v-if="isSingQuesMod"
        :type="2"
        :showAnalysis="showAnalysis"
        :showHistory="showHistory"
        :showQuestion="showQuestionContent"
        :onViewQuestion="handleViewQuestion"
        :onViewAnalysis="onViewAnalysis"
        :onViewHistory="onViewHistory"
        :onRandom="handleRandomQuestion"
        :onPrev="handlePrevQuestion"
        :onNext="handleNextQuestion"
        :analysisData="analysisData"
        :historyData="historyData"
      ></answer-page-foot>
    </div>
  </div>
</template>

<script lang="ts">
import QuestionDetailHead from '@/components/panels/QuestionDetailHead.vue';
import AnswerTopTitle from '@/components/panels/AnswerTopTitle.vue';
import AnswerHead from '@/components/panels/AnswerHead.vue';
import AnswerAnalysis from '@/components/panels/AnswerAnalysis.vue';
import CommitHistory from '@/components/panels/CommitHistory.vue';
import AnswerPageFoot from '@/components/panels/AnswerPageFoot.vue';

import { Options, Vue } from 'vue-class-component';
import { ElMessage } from 'element-plus';
import { PROGRAMURL } from '@/utils/constants';

@Options({
  props: {
    isSingQuesMod: Boolean, // 是否是单题目模式（题库）
    fixed: Boolean,
    isExam: Boolean,
    title: String,
    questionTypeName: String,
    time: String,
    analysisData: Object,
    historyData: Object,
    showAnalysis: Boolean,
    showHistory: Boolean,
    quesData: Object,
    onChange: Function,
    onClose: Function,
    onViewAnalysis: Function,
    onViewHistory: Function,
    onRandom: Function,
    onPrev: Function,
    onNext: Function,
    onDeleteCommitHistory: Function,
    onSave: Function,
    lang: Number,
  },
  components: {
    AnswerTopTitle,
    QuestionDetailHead,
    AnswerHead,
    AnswerAnalysis,
    CommitHistory,
    AnswerPageFoot,
  },
})
export default class Program extends Vue {
  $refs: ObjectT = {};
  $store: any;
  time!: string;
  $confirm: any;
  quesData: ObjectT = {};
  onChange!: () => {};
  onClose!: () => {};
  onRandom!: () => {};
  onPrev!: () => {};
  onNext!: () => {};
  onSave!: (type: number, totalSort: number, value: string) => {};
  pageBodyHeight = 0;
  showQuestionContent = true; // 是否显示题目
  lang!: number; // 2=scratch,3=python
  langName = '';
  isSave = false;
  token = localStorage.getItem('token');
  PROGRAMURL = PROGRAMURL;

  mounted() {
    this.setLangName();
    this.calcPageBodyHeight();
    window.addEventListener('resize', () => {
      this.calcPageBodyHeight();
    });
  }

  // 设置编程题类型名称
  setLangName() {
    switch (this.quesData.lang) {
      case 2:
        this.langName = 'scratch';
        break;
      case 3:
        this.langName = 'python';
        break;
      default:
        break;
    }
  }

  // 计算主体页面高度
  calcPageBodyHeight() {
    const pageHead: any = this.$refs.pageHead;
    const pageFoot: any = this.$refs.pageFoot ? this.$refs.pageFoot.$el : null;
    const pageHeadH = pageHead ? pageHead.getBoundingClientRect().height : 0;
    const pageFootH = pageFoot ? pageFoot.getBoundingClientRect().height : 0;
    this.pageBodyHeight = document.body.clientHeight - pageHeadH - pageFootH - 80;
  }

  // 处理面板关闭
  handleClose() {
    this.handleSave(this.onClose);
  }

  // 处理题目内容显示
  handleViewQuestion() {
    this.showQuestionContent = !this.showQuestionContent;
  }

  // 处理下一题
  // 处理点击随机一题
  handleRandomQuestion() {
    if (this.onRandom) {
      this.onRandom();
    }
    this.showQuestionContent = true;
  }
  // 处理点击上一题
  handlePrevQuestion() {
    if (this.onPrev) {
      this.onPrev();
    }
    this.showQuestionContent = true;
  }
  // 处理点击下一题
  handleNextQuestion() {
    if (this.onNext) {
      this.onNext();
    }
    this.showQuestionContent = true;
  }

  // 处理保存
  handleSave(successCb: () => {}) {
    this.$refs.iframe.contentWindow.uploadCode((data: ObjectT) => {
      if (data.code === 10002) {
        ElMessage.error(data.msg ? data.msg : '保存失败');
        this.$store.commit('setLoginVisible', true);
        return;
      }

      if (data.code) {
        ElMessage.error(data.msg ? data.msg : '保存失败');
        return;
      }
      this.isSave = true;
      if (successCb instanceof Function) {
        successCb();
      } else {
        ElMessage.success(data.msg ? data.msg : '保存成功');
      }
      if (this.onSave) {
        this.onSave(5, this.quesData.totalSort, data.data);
      }
    });
  }
}
</script>

<style scoped lang="scss">
@import './program.scss';
</style>
<style lang="scss">
.side-sheet {
  .q-cont {
    img {
      display: inline-block;
      vertical-align: middle;
      max-width: 95%;
    }
  }
}
.el-message {
  z-index: 10000 !important;
}
</style>
